package com.glela.common.util;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class ExtendMethod {
	public static String getCurrentTime() {
		return getDateTimeStr(Calendar.getInstance(), "HH:mm:ss");
	}

	public static String getCurrentDate() {
		return getDateTimeStr(Calendar.getInstance(), "yyyy-MM-dd");
	}

	public static String getCurrentDateTime() {
		return getDateTimeStr(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss");
	}

	public static String getDateTimeStr(Calendar calendar, String style) {
		return new SimpleDateFormat(style).format(calendar.getTime());
	}

	public static String getDateStr(String datestr, String defaultstr,
			String style) {
		// System.out.println("datestr="+datestr);
		if ((datestr == null) || (datestr.trim().length() == 0))
			return defaultstr;

		if (datestr.length() <= 10)
			datestr = datestr + " 00:00:00";

		SimpleDateFormat sdf = null;
		if (datestr.indexOf("/") > -1) {
			sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		} else {
			sdf = new SimpleDateFormat(style);
		}

		Date date = sdf.parse(datestr, new ParsePosition(0));
		if (date == null)
			return defaultstr;

		if (datestr.indexOf("/") > -1) {
			sdf = new SimpleDateFormat(style);
		}
		return sdf.format(date);
	}

	public static String getDateStr(String datestr, String defaultstr,
			String sStyle, String tStyle) {
		// System.out.println("datestr="+datestr);
		if ((datestr == null) || (datestr.trim().length() == 0))
			return defaultstr;

		if (datestr.length() <= 10)
			datestr = datestr + " 00:00:00";

		SimpleDateFormat sdf = new SimpleDateFormat(sStyle);

		Date date = sdf.parse(datestr, new ParsePosition(0));
		if (date == null)
			return defaultstr;

		sdf = new SimpleDateFormat(tStyle);

		return sdf.format(date);
	}

	public static String getShortDate(String datestr, String defaultstr) {
		return getDateStr(datestr, defaultstr, "yyyy-MM-dd");
	}

	public static String getShortDate(String datestr) {
		return getShortDate(datestr, "");
	}

	public static String getLongDate(String datestr, String defaultstr) {
		return getDateStr(datestr, defaultstr, "yyyy-MM-dd HH:mm:ss");
	}

	public static String getLongDate(String datestr) {
		return getLongDate(datestr, "");
	}

	public static String getTimePart(Calendar calendar, String v) {
		if ((v == null) || (calendar == null)) {
			return "";
		}

		if (v.equalsIgnoreCase("y"))
			return String.valueOf(calendar.get(1));
		if (v.equalsIgnoreCase("M"))
			return StringEx.intToNLengthString(2, calendar.get(2) + 1);
		if (v.equalsIgnoreCase("d"))
			return StringEx.intToNLengthString(2, calendar.get(5));

		return "";
	}

	public static String getCurrentDate(String v) {
		return getTimePart(Calendar.getInstance(), v);
	}

	public static Date strDateTimeToDate(String str) {
		if ((str == null) || (str.trim().length() == 0))
			return null;

		if (str.length() <= 10) {
			str = str + " 00:00:00";
		}

		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str,
				new ParsePosition(0));
	}
	
	public static Date strDateTimeToDateEx(String str) {
		if ((str == null) || (str.trim().length() == 0))
			return null;

		if (str.length() <= 10) {
			str = str + " 00:00:00.000";
		}

		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(str,
				new ParsePosition(0));
	}

	public static Calendar strDateTimeToCalendar(String str) {
		Calendar calendar = Calendar.getInstance();
		Date date = strDateTimeToDate(str);
		if (date == null)
			return null;

		calendar.setTime(date);
		return calendar;
	}

	public static String dateToStrDateTime(Date date) {
		if (date == null)
			return null;

		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}

	public static String calendarToStrDateTime(Calendar calendar) {
		if (calendar == null)
			return null;

		return dateToStrDateTime(calendar.getTime());
	}

	public static String getTargetDateType(String datestr, String v) {
		return getTimePart(strDateTimeToCalendar(datestr), v);
	}

	public static int compareTwoDate(String srcdate, String tagdate) {
		Calendar scalendar = strDateTimeToCalendar(srcdate);
		Calendar tcalendar = strDateTimeToCalendar(tagdate);
		if ((scalendar == null) || (tcalendar == null))
			return -2;

		return scalendar.getTime().compareTo(tcalendar.getTime());
	}

	public static String getChineseDate(String datestr) {
		Calendar calendar = strDateTimeToCalendar(datestr);
		if (calendar == null)
			return "";

		return new SimpleDateFormat("yyyy年M月d日").format(calendar.getTime());
	}

	public static String mathDate(String srcdate, int intdate) {
		Calendar calendar = strDateTimeToCalendar(srcdate);
		if (calendar == null)
			return "";

		calendar.add(5, intdate);
		return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
	}

	public static String mathLongDate(String srcdate, long longms) {
		Calendar calendar = strDateTimeToCalendar(srcdate);
		if (calendar == null)
			return "";

		calendar.add(14, (int) longms);
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar
				.getTime());
	}

	public static int mathTwoDate(String sdatestr, String tdatestr) {
		Calendar scalendar = strDateTimeToCalendar(sdatestr);
		Calendar tcalendar = strDateTimeToCalendar(tdatestr);
		if ((scalendar == null) || (tcalendar == null))
			return 0;

		return (int) ((tcalendar.getTimeInMillis() - scalendar
				.getTimeInMillis()) / 86400000L);
	}

	public static long mathTwoLongDate(String sdatestr, String tdatestr) {
		Calendar scalendar = strDateTimeToCalendar(sdatestr);
		Calendar tcalendar = strDateTimeToCalendar(tdatestr);
		if ((scalendar == null) || (tcalendar == null))
			return 0L;

		return mathTwoCalendar(scalendar, tcalendar);
	}

	public static long mathTwoCalendar(Calendar scalendar, Calendar tcalendar) {
		return (scalendar.getTimeInMillis() - tcalendar.getTimeInMillis());
	}

	public static String getDateMonth(String dtstr) {
		return getDateStr(dtstr, "", "yyyy-MM");
	}

	public static String[] getAllMonth(String frommonth, String tomonth) {
		Calendar fcalendar = strDateTimeToCalendar(frommonth);
		Calendar tcalendar = strDateTimeToCalendar(tomonth);
		if ((fcalendar == null) || (tcalendar == null)) {
			return null;
		}

		if ((fcalendar.after(tcalendar))
				&& (((fcalendar.get(1) != tcalendar.get(1)) || (fcalendar
						.get(2) != tcalendar.get(2))))) {
			return null;
		}

		ArrayList<String> aList = new ArrayList<String>();
		aList.add(new SimpleDateFormat("yyyy-MM-01").format(fcalendar.getTime()));
		fcalendar.add(2, 1);
		while ((fcalendar.get(1) < tcalendar.get(1))
				|| ((fcalendar.get(1) == tcalendar.get(1)) && (fcalendar.get(2) <= tcalendar
						.get(2)))) {
			aList.add(new SimpleDateFormat("yyyy-MM-01").format(fcalendar
					.getTime()));
			fcalendar.add(2, 1);
		}

		return ((String[]) aList.toArray(new String[aList.size()]));
	}

	public static String[] getAllDay(String sdatestr, String tdatestr) {
		Calendar scalendar = strDateTimeToCalendar(sdatestr);
		Calendar tcalendar = strDateTimeToCalendar(tdatestr);
		if ((scalendar == null) || (tcalendar == null)) {
			return null;
		}

		if ((tcalendar.getTimeInMillis() - scalendar.getTimeInMillis()) / 86400000L < 0L) {
			return null;
		}

		ArrayList<String> aList = new ArrayList<String>();
		aList.add(new SimpleDateFormat("yyyy-MM-dd").format(scalendar.getTime()));
		scalendar.add(5, 1);
		while ((tcalendar.getTimeInMillis() - scalendar.getTimeInMillis()) / 86400000L >= 0L) {
			aList.add(new SimpleDateFormat("yyyy-MM-dd").format(scalendar
					.getTime()));
			scalendar.add(5, 1);
		}

		return ((String[]) aList.toArray(new String[aList.size()]));
	}

	public static String changeToHtmlString(String srcstr) {
		if ((srcstr == null) || (srcstr.trim().length() == 0)) {
			return "";
		}

		StringBuffer result = new StringBuffer();
		StringCharacterIterator iterator = new StringCharacterIterator(srcstr);
		char character = iterator.current();
		while (character != 65535) {
			if (character == '<')
				result.append("&lt;");
			else if (character == '>')
				result.append("&gt;");
			else if (character == '"')
				result.append("&quot;");
			else if (character == '\'')
				result.append("&#039;");
			else if (character == '\\')
				result.append("&#092;");
			else if (character == '&')
				result.append("&amp;");
			else if (character == ' ')
				result.append("&nbsp;&nbsp");
			else if (character == '\n') {
				result.append("<br>");
			} else {
				result.append(character);
			}
			character = iterator.next();
		}
		return result.toString();
	}

	public static int getRandomInt(int s, int e) {
		return (int) (Math.random() * (e - s) + s);
	}

	public static String getFloatString(String fstr, int l) {
		return strToBigDecimal(fstr).setScale(l, 4).toString();
	}

	/**
	 * @deprecated
	 */
	public static String checkTechCount(String fstr) {
		return fstr;
	}

	public static BigDecimal strToBigDecimal(String str) {
		BigDecimal ret;
		if ((str == null) || (str.trim().length() == 0))
			ret = new BigDecimal("0");
		else
			try {
				ret = new BigDecimal(str);
			} catch (Exception ex) {
				ret = new BigDecimal("0");
			}

		return ret;
	}

	public static Integer strToInteger(String str) {
		Integer ret;
		if ((str == null) || (str.trim().length() == 0))
			ret = new Integer("0");
		else
			try {
				ret = new Integer(str);
			} catch (Exception ex) {
				ret = new Integer("0");
			}

		return ret;
	}

	public static String filterRepeatStrs(String strs, String separator) {
		if (strs == null || strs.isEmpty()) {
			return "";
		}
		StringBuilder stringBuilder = new StringBuilder();
		String arr[] = strs.split(separator);
		Map<String, String> map = new HashMap<String, String>();
		for (String string : arr) {
			map.put(string, string);
		}
		for (Map.Entry<String, String> entry : map.entrySet()) {
			stringBuilder.append(entry.getValue()).append(",");
		}
		String result = stringBuilder.toString();
		if (result != null && result.endsWith(",")) {
			result = result.substring(0, result.length() - 1);
		}
		return result;
	}

	public static boolean isRelationStrs(String strs, String strs2,
			String separator) {
		boolean bool = false;
		String arr[] = strs.split(separator);
		for (String string : arr) {
			if (("," + strs2 + ",").indexOf("," + string + ",") > -1) {
				bool = true;
				break;
			}
		}
		return bool;
	}

	public static String filterRelationStrs(String strs, String strs2,
			String separator) {
		StringBuilder stringBuilder = new StringBuilder();
		String arr[] = strs2.split(separator);
		for (String string : arr) {
			if (("," + strs + ",").indexOf("," + string + ",") > -1) {
				stringBuilder.append(string).append(",");
			}
		}
		String str = stringBuilder.toString();
		if (str.endsWith(",")) {
			str = str.substring(0, str.length() - 1);
		}
		return str;
	}

	public static int getFloatSum(String[] sumvalue) {
		if (sumvalue == null) {
			return 0;
		}

		BigDecimal ret = new BigDecimal("0");
		for (int i = 0; i < sumvalue.length; ++i) {
			BigDecimal sum = strToBigDecimal(sumvalue[i]);
			if (sum != null)
				ret = ret.add(sum);

		}

		ret = ret.multiply(new BigDecimal("100")).setScale(0, 4);
		return ret.intValue();
	}

	public static String getAnotherManID(String mid) {
		if (mid == null)
			return "";

		StringBuffer another = new StringBuffer();
		if (mid.length() == 15) {
			StringBuffer temp = new StringBuffer().append(mid.substring(0, 6))
					.append("19").append(mid.substring(6));
			int value = 0;
			char[] checkID = { '1', '0', 'X', '9', '8', '7', '6', '5', '4',
					'3', '2' };
			int[] multiID = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4,
					2, 1 };
			for (int i = 0; i < temp.length(); ++i)
				value = value
						+ Integer.parseInt(String.valueOf(temp.charAt(i)))
						* multiID[i];

			value = value % 11;
			another.append(temp).append(checkID[value]);
		} else if (mid.length() == 18)
			another.append(mid.substring(0, 6)).append(mid.substring(8, 17));
		else
			another.append(mid);

		return another.toString();
	}

	public static String getBirthdayOrSexByManID(String mid, int BorS) {
		StringBuffer birthday;
		char csex;
		if ((mid == null) || (mid.trim().length() == 0)) {
			birthday = new StringBuffer(getCurrentDate());
			csex = '1';
		} else {
			char[] manarr = mid.toCharArray();
			if (manarr.length == 18) {
				birthday = new StringBuffer().append(manarr[6])
						.append(manarr[7]).append(manarr[8]).append(manarr[9])
						.append("-").append(manarr[10]).append(manarr[11])
						.append("-").append(manarr[12]).append(manarr[13]);

				csex = manarr[16];
			} else if (manarr.length == 15) {
				birthday = new StringBuffer().append("19").append(manarr[6])
						.append(manarr[7]).append("-").append(manarr[8])
						.append(manarr[9]).append("-").append(manarr[10])
						.append(manarr[11]);

				csex = manarr[14];
			} else {
				birthday = new StringBuffer(getCurrentDate());
				csex = '1';
			}
		}
		if (BorS == 0)
			return birthday.toString();

		if (Integer.parseInt(String.valueOf(csex)) == 2)
			return "女";

		return "男";
	}

	public static String[] sortintStringArray(String[] stra) {
		if ((stra == null) || (stra.length <= 1)) {
			return stra;
		}

		int[] inta = StringEx.toIntArray(stra);
		if (inta == null)
			return stra;

		Arrays.sort(inta);
		return StringEx.toStringArray(inta);
	}

	public static String changeRichTextToString(String srcstr) {
		if ((srcstr == null) || (srcstr.length() == 0))
			return "";

		return srcstr.replaceAll("#!", "<").replaceAll("!#", ">");
	}

	public static int getWeekNumber() {
		Calendar calendar = Calendar.getInstance();
		calendar.setFirstDayOfWeek(Calendar.MONDAY);

		calendar.setTime(new Date());
		return calendar.get(Calendar.WEEK_OF_YEAR);

	}

	public static String getMonthLastDay(String year, String month) {
		if ((month == null) || (month.trim().length() == 0)) {
			return "";
		}
		String monthStr = "04,06,09,11";
		if (monthStr.indexOf(month) > -1) {
			return "30";
		} else if (month.equals("02")) {
			String temp = ExtendMethod.mathDate(year + "-03-01", -1);
			return temp.substring(temp.lastIndexOf("-") + 1);
		} else {
			return "31";
		}
	}

	/**
	 * 获取菜单图标字符串
	 * 
	 * @param request
	 * @param path
	 * @param srcPath
	 * @param selectedValue
	 * @return
	 */
	public static String getMenuIcoString(HttpServletRequest request,
			String path, String srcPath, String selectedValue) {
		String str = "";
		StringBuilder stringBuilder = new StringBuilder();
		String realPath = request.getSession().getServletContext().getRealPath("/admin/images/menuico/");
		List<File> fileList = FileUtil.getFileList(realPath);
		int i = 0;
		if (fileList != null) {
			for (File file : fileList) {
				if (!file.getName().endsWith(".db")) {
					stringBuilder
							.append("<input type='radio' name='ico' value='")
							.append(file.getName()).append("'");
					if (file.getName().equals(selectedValue)) {
						stringBuilder.append("checked");

					}
					stringBuilder.append("/><img src='").append(srcPath)
							.append(file.getName()).append("'/>");
					i++;
					if (i % 6 == 0) {
						stringBuilder.append("<br>");
					}
				}
			}
		}
		str = stringBuilder.toString();
		if (str.endsWith("<br>")) {
			str.substring(0, str.length() - 4);
		}
		return stringBuilder.toString();
	}

	public static String[] getCurrentQuarter(int month) {
		if (month >= 1 && month <= 3) {
			return new String[] { "01", "03" };
		} else if (month >= 4 && month <= 6) {
			return new String[] { "04", "06" };
		} else if (month >= 7 && month <= 9) {
			return new String[] { "07", "09" };
		} else if (month >= 10 && month <= 12) {
			return new String[] { "10", "12" };
		} else {
			return null;
		}
	}

	public static int getWeekDay(Date dt) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);

		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return w;
	}

	public static String formatDecimal(String format, double value) {
		DecimalFormat decimalformat = new DecimalFormat(format);
		return decimalformat.format(value);
	}

	public static String format2DataSize(String format, double n) {
		String arr[] = { "Byte", "K", "M", "G", "T" };
		int i = 0;
		while ((n = n / 1024) >= 1) {
			i++;
		}
		return formatDecimal(format, n * 1024) + arr[i];
	}

	public static void main(String[] args) {
		// System.out.println(getLongDate("10/10/2012 9:10:30", ""));
		// System.out.println(getWeekNumber());
		// String a = "a#1";
		// String arr[] = a.split("#");
		// System.out.println(arr[0]);
		// System.out.println(arr[1]);
		// System.out.println(mathDate("2011-11-30", 1));
		// System.out.println(getDateStr("2/27/2013 15:2:39", "",
		// "MM/dd/yyyy HH:mm:ss", "yyyy-MM-dd HH:mm"));
		// System.out.println(getMonthLastDay("2012", "02"));
		// System.out.println(getCurrentDate("M"));
		 System.out.println(getDateStr("2013-03-22 05:20:01.0", "",
		 "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm"));
//		System.out.println(format2DataSize("0.0", 1725));
		System.out.println(mathTwoDate("2016-10-29 14:23:04", "2016-11-01 10:11:04"));
	}

}